<!--
 * @Author: wangming
 * @Date: 2021-05-12 16:36:21
 * @LastEditors: wangming
 * @LastEditTime: 2022-02-11 11:37:27
 * @Description: file content
-->
<template>
  <el-dialog
    width="900px"
    :visible.sync="visible"
    center
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ options.title }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleClosed"></span>
      </div>
    </div>
    <div id="render-jsx-editor"></div>
    <div slot="footer" class="tr">
      <el-button @click="handleClosed">取消</el-button>
      <el-button type="primary" @click="handleDialogConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
import { Dialog, Button, Message } from "element-ui";
const DEFAULT_OPTIONS = {
  title: "自定义渲染函数",
  content: "",
  onConfirm: undefined,
};
export default {
  components: {
    [Button.name]: Button,
    [Dialog.name]: Dialog,
  },
  data() {
    return {
      visible: false,
      content: null,
      options: {
        ...DEFAULT_OPTIONS,
      },
    };
  },
  methods: {
    init(options) {
      this.options = {
        ...DEFAULT_OPTIONS,
        ...options,
      };
      this.content = this.options.content
        ? decodeURIComponent(this.options.content)
        : "";
      this.visible = true;
      this.initEditor();
    },

    async initEditor() {
      await this.$nextTick();
      this._renderJsxEditor = monaco.editor.create(
        document.getElementById("render-jsx-editor"),
        {
          value: this.content,
          language: "javascript",
          minimap: {
            enabled: false,
          },
        }
      );
    },

    handleClosed() {
      if (this._renderJsxEditor) {
        this._renderJsxEditor.dispose();
        this._renderJsxEditor = null;
      }
      this.visible = false;
    },

    handleDialogConfirm() {
      const error = monaco.editor
        .getModelMarkers()
        .filter((i) => i.code !== "6133" && i.code !== "2339");
      if (error.length > 0) {
        Message.error("语法错误" + error[0]?.message);
        return;
      }
      let content = this._renderJsxEditor.getValue() + "";
      content && (content = encodeURIComponent(content));
      this.options.onConfirm && this.options.onConfirm(content);
      this.handleClosed();
    },
  },
};
</script>

<style scoped>
#render-jsx-editor {
  height: 45vh;
}
</style>
